package com.lzp.user.controller;


import com.lzp.common.result.PageResult;
import com.lzp.common.result.Result;
import com.lzp.user.pojo.dto.UserDTO;
import com.lzp.user.pojo.dto.UserLoginDTO;
import com.lzp.user.pojo.dto.UserOrderDTO;
import com.lzp.user.pojo.vo.UserLoginVO;
import com.lzp.user.pojo.vo.UserVO;
import com.lzp.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;



@RequestMapping("/user")
@RestController
@Api(tags = "用户管理")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @GetMapping("/{id}")
    @ApiOperation("根据id获取用户")
    public Result<UserVO> getUser(@PathVariable("id") Long id){
        return Result.success(userService.getUserById(id));
    }

    @GetMapping("/list")
    @ApiOperation("获取全部用户")
    public Result<PageResult> list(){
        return Result.success(userService.queryAllUsers());
    }

    @GetMapping("/page")
    @ApiOperation("分页查询用户")
    public Result<PageResult> page(Integer pageNo, Integer pageSize){
        return Result.success(userService.pageUsers(pageNo, pageSize));
    }

    @PostMapping("/save")
    @ApiOperation("新增用户")
    public Result<String> save(@Validated @RequestBody UserDTO user){
        return userService.addUser(user) ? Result.success("添加成功") : Result.error("添加失败");
    }

    @PostMapping("/saveUserAndOrder")
    @ApiOperation("同时新增用户和订单")
    public Result<String> save(@Validated @RequestBody UserOrderDTO userOrderDTO){
        return userService.addUserAndOrder(userOrderDTO.getUserDTO(), userOrderDTO.getOrderDTO()) ? Result.success("添加成功") : Result.error("添加失败");
    }

    @PutMapping("/update")
    @ApiOperation("更新用户")
    public Result<String> update(@RequestBody UserDTO user){
        return userService.updateUser(user) ? Result.success("更新成功") : Result.error("更新失败");
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户")
    public Result<String> delete(@PathVariable("id") Long id){
        return userService.deleteUser(id) ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录：{}", userLoginDTO);
        // 根据UserLoginDTO进行登录
        return Result.success(userService.login(userLoginDTO));
    }

}
